package server.socket.handler.chat;

import server.socket.bean.Message;
import server.socket.db.ChatModel;
import server.socket.handler.InfoHandler;
import server.socket.server.ChatServer;
import server.util.InfoUtils.Info;
import server.util.InfoUtils.InfoUtil;
import server.util.MyUtils;

import java.util.List;

public class ChatInfoHandler extends InfoHandler {
    private ChatClientHandler clientHandler;

    public void setClientHandler(ChatClientHandler clientHandler) {
        this.clientHandler = clientHandler;
    }


    @Override
    public Info handleInfo(Info info) {
        switch (info.getCode()) {
            case 0:
                //将info中的data(json)转化为message实体
                Message message = MyUtils.fromJson(info.getData().toString(), Message.class);
                System.out.println(message);
                clientHandler.sendMessage2Server(message);
                break;
            case 2:
                //登录后即在服务端注册表示上线
                Integer userId = (Integer) info.getData();
                clientHandler.setUserId(userId);//注册
                ChatServer.getChatServer().sendToClient(userId, InfoUtil.getInfo(0, "注册成功"));
                //发送未接收的离线消息
                List<Message> messages = ChatModel.getMessage(userId);
                for (Message msg : messages) {
                    //将msg里的json转化为Message
                    Message endMsg = MyUtils.fromJson(msg.getJson(), Message.class);
                    ChatServer.getChatServer().sendToClient(userId, endMsg);
                }
                System.out.println("User<" + userId + ">注册成功");
                break;
        }
        return null;
    }
}
